package com.itheima.controller;


import com.itheima.bean.vo.*;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
//@CrossOrigin(origins ={"http://localhost:8090","null"} )
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 分页查询用户数据
     *
     * @param currentPage 页码
     * @param pageSize    每页条数
     * @return
     */
    @GetMapping("/{currentPage}/{pageSize}")
//    @CrossOrigin
    public Result selectUserByPage(@PathVariable Integer currentPage,
                                   @PathVariable Integer pageSize) {
        Pagination pagination = new Pagination();
        //创建分页对象
        pagination.setCurrentPage(currentPage);
        pagination.setPageSize(pageSize);
        PageBean pageBean = userService.queryUserByPage(pagination);
        Result responseResult =  new Result(Code.GET_ERR,"查询失败");
        if(pageBean!=null){
          responseResult = new Result(Code.GET_OK,pageBean,"查询成功");
        }

        return responseResult;
    }

    /**
     * 添加用户
     *
     * @param user 前端传递的请求参数对象：要添加的用户
     * @return
     */
@PostMapping("/add")
@CrossOrigin
    public Result addUser(@RequestBody AddUser user) {

        boolean result = userService.addUserAndRole(user);
        Result responseResult = new Result(Code.SAVE_ERR, "保存失败");//默认：失败
        if(result){
            responseResult = new Result(Code.SAVE_OK, result,"保存成功");
        }
        return responseResult;

    }
@PostMapping("/update")
    @CrossOrigin
    public Result updateUser(@RequestBody UpdateUser user){
    boolean resullt =userService.updateUserAndRole(user);
    Result responseResult = new Result(Code.UPDATE_ERR, "更新失败");
    if(resullt){
        responseResult=new Result(Code.UPDATE_OK,resullt,"更新成功");
    }
    return responseResult;
}

}
